from pyspades.server import block_action
from pyspades.collision import distance_3d_vector
from commands import add, admin
from map import Map
from pyspades.constants import *
import commands

@admin
def floor(connection):
        if connection.flooring > 0:
            connection.flooring = 0
            return 'Floor generator cancelled'
        else:
            connection.flooring = 1
            return 'Place first corner block'
add(floor)

def apply_script(protocol, connection, config):
    class floorMakerConnection(connection):
        flooring = 0
        floor_x = 0
        floor_y = 0
        floor_z = 0

        def build_floor(self, first_x, first_y, first_z, second_x, second_y):
            for build_x in xrange(min(first_x , second_x) , max(first_x , second_x)+1):
                for build_y in xrange(min(first_y , second_y) , max(first_y , second_y)+1):
                    if self.god_build:
                        if self.protocol.god_blocks is None:
                            self.protocol.god_blocks = set()
                        self.protocol.god_blocks.add((build_x, build_y, first_z))
                    block_action.x = build_x
                    block_action.y = build_y
                    block_action.z = first_z
                    block_action.player_id = self.player_id
                    block_action.value = BUILD_BLOCK
                    self.protocol.send_contained(block_action, save = True)
                    self.protocol.map.set_point(build_x, build_y, first_z, self.color+(255,), user = False)
            self.send_chat('Floor complete!')

        def on_block_build(self, x, y, z):
            if self.flooring == 2:
                if self.floor_z == z:
                    self.build_floor(self.floor_x, self.floor_y, self.floor_z, x, y)
                    self.flooring = 0
                else:
                    self.send_chat('Surface is uneven! Using first height.')
                    self.build_floor(self.floor_x, self.floor_y, self.floor_z, x, y)
                    self.flooring = 0
            if self.flooring == 1:
                self.floor_x = x
                self.floor_y = y
                self.floor_z = z
                self.send_chat('Now place opposite corner block')
                self.flooring = 2
            return connection.on_block_build(self, x, y, z)

                
    return protocol, floorMakerConnection